package com.yutianran.ezadapter.rv;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.yutianran.ezadapter.CommonViewHolder;
import com.yutianran.ezadapter.LayoutPlayer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RvAdapter extends RecyclerView.Adapter<CommonViewHolder> {

    private List<?> data;
    private RvHelper helper;
    private Map<Integer, Integer> viewType2layoutId = new HashMap<>();//viewType --> layoutId
    private Map<Integer, Integer> layoutId2viewType = new HashMap<>();//layoutId --> viewType

    public RvAdapter(RvHelper helper) {
        this.helper = helper;
    }

    public RvAdapter(RvHelper helper, List<?> data) {
        this.helper = helper;
        this.data = data;
    }

    public void initLayoutIdMap() {
        for (int i = 0; i < helper.getLayoutIds().size(); i++) {
            viewType2layoutId.put(i, helper.getLayoutIds().get(i));
            layoutId2viewType.put(helper.getLayoutIds().get(i), i);
        }
    }

    @Override
    public CommonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Integer layoutId = viewType2layoutId.get(viewType);
        return new CommonViewHolder(LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull CommonViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        int layoutId = viewType2layoutId.get(viewType);
        LayoutPlayer<?> player = helper.getPlayerMap().get(layoutId);
        convert(player, data.get(position), holder);
    }

    private <T> void convert(LayoutPlayer<T> player, Object obj, CommonViewHolder holder) {
        T t = (T) obj;
        player.bindData(t, holder);
    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    public int getItemViewType(int position) {
        Object item = data.get(position);
        Class<?> clazz = item.getClass();
        Map<Class, Integer> layoutIdMap = helper.getLayoutIdMap();
        Integer layoutId = layoutIdMap.get(clazz);
        Integer viewType = layoutId2viewType.get(layoutId);
        return viewType;
    }

    public void setData(List<?> data) {
        this.data = data;
        notifyDataSetChanged();
    }


}
